﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WaveSim.Core.Data.Parser;
using System.Reflection;

namespace WaveSim.Core.Equations.Galerkin
{
    public class WaveGuide : ICodable
    {
        private static Dictionary<string, PropertyInfo> properties;

        public WaveGuide()
        {
            properties = new Dictionary<string, PropertyInfo>();
            foreach (var property in typeof(WaveGuide).GetProperties())
            {
                properties.Add(property.Name, property);
            }
        }

        public WaveGuide(double a, double b, double l)
            : this()
        {
            A = a;
            B = b;
            L = l;
        }

        public double A { get; private set; }

        public double B { get; private set; }

        public double L { get; private set; }

        #region ICodable
        string ICodable.Code()
        {
            StringBuilder code = new StringBuilder();
            code.AppendFormat("#{0}", this.GetType().Name);
            foreach (var keyValue in properties)
            {
                code.AppendFormat("\n\t{0}={1}", keyValue.Key, keyValue.Value.GetValue(this, null));
            }
            return code.ToString();
        }

        object ICodable.Decode(string txt)
        {
            string[] lines = txt.Split('\n');
            foreach (var code in lines)
            {
                string[] keyValue = code.Split('=');
                if (keyValue.Length <= 1)
                    continue;
                string key = Process(keyValue[0]);
                string val = Process(keyValue[1]);
                if (properties.ContainsKey(key))
                {
                    Type t = properties[key].PropertyType;
                    properties[key].SetValue(this, Convert.ChangeType(val, t), null);
                }
            }
            return this;
        }
        #endregion

        private static string Process(string str)
        {
            return str
                .Replace("\r", String.Empty)
                .Replace("\t", String.Empty)
                .Replace("\n", String.Empty)
                .Trim();
        }
    }
}
